package icu.study.common.security.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.interfaces.DecodedJWT;
import icu.study.common.security.constant.JwtConstant;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * @description: jwt工具嘞
 * @author: 伊利丹·怒风
 */
public class JwtUtil {


    /*
     * @param subject 携带的subject参数
     * @return java.lang.String token
     * @description: 生成一个token
     */
    public static String createToken(String subject) {
        Calendar instance = reloadCalendar();
        Map<String, Object> map = new HashMap<>(); //头部 默认也是HMAC256
        String token = JWT.create().withHeader(map)
                .withSubject(subject)
                .withExpiresAt(instance.getTime())
                .sign(JwtConstant.algorithm);
        return token;
    }

    /*
     * @param authorities 所有角色,subject 携带的subject参数  --权限认证专用方法
     * @return java.lang.String token
     * @description: 生成一个token
     */
    public static String createToken(String authorities, String subject) {
        Calendar instance = reloadCalendar();
        Map<String, Object> map = new HashMap<>(); //头部 默认也是HMAC256
        String token = JWT.create().withHeader(map)
                .withClaim("authorities", authorities)
                .withSubject(subject)
                .withExpiresAt(instance.getTime())
                .sign(JwtConstant.algorithm);
        return token;
    }


    /*
     * @param subject Map<String, String> params 参数
     * @return java.lang.String token
     * @description: 生成一个token
     */
    public static String createToken(Map<String, String> params) {

        Calendar instance = reloadCalendar();
        Map<String, Object> map = new HashMap<>(); //头部 默认也是HMAC256
        JWTCreator.Builder builder = JWT.create().withHeader(map);
        params.forEach((key, value) -> builder.withClaim(key, params.get(key)));
        String token = builder
                .withExpiresAt(instance.getTime())
                .sign(JwtConstant.algorithm);
        return token;
    }

    /*
     * @description: 重载calendar
     */
    private static Calendar reloadCalendar() {
        Calendar instance = Calendar.getInstance();
        instance.add(JwtConstant.EXPIRES_TIME_TYPE, JwtConstant.EXPIRES_TIME_AMOUNT);
        return instance;
    }

    /*
     * @param String token
     * @return DecodedJWT 解码的jwt
     * @description: 验证token
     */
    public static DecodedJWT verifyToken(String token) {
        DecodedJWT verify = null;
        try {
            verify = JwtConstant.jwtVerifier.verify(token);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return verify;
    }

}